package com.elecbook.auth.model.po;

import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Data
public class LoginsUserDetail implements UserDetails {
    private User user;
    List<String> roleNames;
    List<String> permissionNames;

    /**
     * description 构造情况，将实体类型User进行放置
     *
     * @author zken
     * CreateDate 2024/11/1 10:18:44
     */
    public LoginsUserDetail(User user) {
        this.user = user;
    }

    /**
     * description 自定义权限
     * springSecurity的默认的Authorities中，
     * 以ROLE_开头的是角色，其余是permission权限，我们的目的是根据我们自己的roleNames和PermissionNames进行Authorities的返回，
     * 交给security的上下文,（交给上下文的位置在UserDetailService，需要重写的时候配合DAO（mysql）进行添加
     *
     * @author zken
     * CreateDate 2024/10/28 00:02:11
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {

        String rolePrefix = "ROLE_";
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        if (roleNames != null) {
            roleNames.forEach(
                    role -> authorities.add(new SimpleGrantedAuthority(rolePrefix + role))
            );
        }
        if (permissionNames != null) {
            permissionNames.forEach(
                    permission -> authorities.add(new SimpleGrantedAuthority(permission))
            );
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getId().toString();
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
}
